package com.zhkj.crawl.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zhkj.crawl.bean.CrawAmzParams;
import com.zhkj.crawl.bean.FetchPhpParams;
import com.zhkj.crawl.config.Config;
import com.zhkj.crawl.config.Constants;
import com.zhkj.crawl.service.impl.BusService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("")
@Slf4j
public class TestController extends BaseController{

    @Autowired
    private BusService busService;

    @XxlJob("fetchPhpData")
    public ReturnT<String> fetchPhpData() {
        String param = XxlJobHelper.getJobParam();
        busService.fetchData(FetchPhpParams.init(param));
        return ReturnT.SUCCESS;
    }

    @XxlJob("test")
    public void test() {
        String param = XxlJobHelper.getJobParam();
        JSONObject ret = new JSONObject();
        ret.put("aa", "bb");
        ret.put("qq", 11);
        log.info("in.............");
        try {
            TimeUnit.SECONDS.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("done.............");
        XxlJobHelper.handleSuccess(ret.toString());
    }

    @XxlJob("pushPhpData")
    public ReturnT<String> pushPhpData() {
        String param = XxlJobHelper.getJobParam();
        busService.doPushPhp();
        return ReturnT.SUCCESS;
    }

    //@Scheduled(initialDelay = 1000 * 5, fixedDelay = 1000 * 60 * 5) // fixedDelay.从上次任务结束时间算 fixedRate.从上次任务开始时间算
    @XxlJob("crawRank")
    public void start(){
        String param = XxlJobHelper.getJobParam();
        long distance = System.currentTimeMillis() - Config.lastFinishTime;
        int min = Constants.isWindows ? 10 : 7;
        if(Config.scheduling || (distance < min * 60 * 1000)){
            return;
        }
        // 休息策略
        if(Config.execTimes >= 10){
            if(Config.restTimes < 2){
                ++Config.restTimes;
                return;
            }
            Config.execTimes = 0;
            Config.restTimes = 0;
            return;
        }

        log.info("定时任务开始:" + param);
        CrawAmzParams params = CrawAmzParams.init(param);
        modifyConfig(params);

        busService.enter(params);
        Config.scheduling = false;
        ++Config.execTimes;
        Config.lastFinishTime = System.currentTimeMillis();
        log.info("定时任务结束");
        closeAllChrome();
    }

    public static void closeAllChrome() {
        if(Config.execTimes % 2 != 0){ return; }

        try {
            String[] cmd = null;
            if(Constants.isWindows){
                cmd = new String[]{"cmd", "/c", "taskkill /IM chrome.exe /F"};
            }else{
                cmd = new String[]{"/bin/sh", "-c", "killall -9 chrome"};
            }
            InputStream ips = Runtime.getRuntime().exec(cmd).getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(ips, "gb2312"));
            String line;
            StringBuilder result = new StringBuilder();
            while ((line = br.readLine()) != null) {
                result.append(line).append("\n");
            }
            log.info("执行命令：{}", result);
        }catch (Exception e){
            log.error("执行cmd错误", e);
        }
    }


    private void modifyConfig(CrawAmzParams params) {
        // 代理开两次 1.200条 2.线程数4
        // 关一次 1.处理400条 2.不用代理速度快,减小线程数为3
        int threadCount = 3;
        if(Config.proxyTimes++ == 2 || !params.isProxy()){
            Config.proxyTimes = 0;
            Config.proxySwitch = false;
            Config.limit = params.getNoProxyCount();
        }else {
            Config.proxySwitch = true;
            threadCount = 4;
            Config.limit = params.getProxyCount();
        }

        if(params.getThreadCount() != null){
            threadCount = params.getThreadCount();
        }

        BusService.modifyThreadSize(threadCount);
        // TEST
//        Config.proxySwitch = false;
//        BusService.modifyThreadSize(3);
//        Config.limit = 300;

        Config.scheduling = true;
    }



}
